﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GoodsService.Application.Contract.DTO.Input;
using GoodsService.Application.Contract.DTO.Output;
using GoodsService.Application.Contract.IAppService;
using LeoGemini.Service.Infrastructure.Constract;
using LeoGemini.Service.Infrastructure.Extension;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;

namespace GoodsService.HttpApi.Hosting.Controller
{
    [Route("api/v1/collections")]
    public class CollectionsController : ApiResponseController
    {
        private readonly ICollectionAppService _collectionAppService;
        private readonly IGoodsAppService _goodsAppService;
        private readonly IWebHostEnvironment _env;

        public CollectionsController(
            IWebHostEnvironment env,
            ICollectionAppService collectionAppService,
            IGoodsAppService goodsAppService)
        {
            _collectionAppService = collectionAppService;
            _goodsAppService = goodsAppService;
            _env = env;
        }

        /// <summary>
        /// 分页获取系列id
        /// </summary>
        [HttpGet]
        public async Task<object> GetCollectionsByPagination(int p, int n = 10)
        {
            return await _collectionAppService.GetCollectionsByPaginationAsync(p - 1, n);
        }
        
        /// <summary>
        /// 根据系列id获取系列信息
        /// </summary>
        [HttpGet("{collectionId}/details")]
        public async Task<object> GetCollectionById(string collectionId)
        {
            return await _collectionAppService.GetCollectionByIdAsync(collectionId);
        }
        
        /// <summary>
        /// 根据系列id分页获取商品id
        /// </summary>
        [HttpGet("{collectionId}/goods")]
        public async Task<object> GetGoodsIdsByCollectionIdAndPagination(string collectionId, int p, int n = 10)
        {
            return await _goodsAppService.GetGoodsIdsByCollectionIdAndPaginationAsync(collectionId, p - 1, n);
        }

        /// <summary>
        /// 添加系列
        /// </summary>
        [HttpPost("create")]
        public async Task<object> CreateCollection(CreateCollectionInputDto dto)
        {
            return await _collectionAppService.CreateCollectionAsync(dto);
        }

        /// <summary>
        /// 删除系列
        /// </summary>
        [HttpDelete("{collectionId}/delete")]
        public async Task DeleteCollectionById(string collectionId)
        {
            await _collectionAppService.DeleteCollectionByIdAsync(collectionId);
        }

        /// <summary>
        /// 修改系列
        /// </summary>
        [HttpPut("{collectionId}/edit")]
        public async Task<object> EditCollectionById(string collectionId, EditCollectionInputDto dto)
        {
            return await _collectionAppService.EditCollectionByIdAsync(collectionId, dto);
        }

        /// <summary>
        /// 导入系列信息excel
        /// </summary>
        [HttpPost("imports")]
        public async Task<object> ImportCollectionExcel(IFormFile file)
        {
            // 写出文件
            var path = file.SaveTo(Path.Combine(_env.WebRootPath, "collection")).Replace('/', '\\');
            return await ExportCollectionsFromExcel(path);
        }
        
        private async Task<ICollection<CreateCollectionReturnDto>> ExportCollectionsFromExcel(string filePath)
        {
            FileInfo file = new FileInfo(filePath);
            using (ExcelPackage package = new ExcelPackage(file))
            {
                var collections = new List<CreateCollectionReturnDto>();
                ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
                //获取表格的列数和行数
                int rowCount = worksheet.Dimension.Rows;
                for (int row = 2; row <= rowCount; row++)
                {
                    var collection = await _collectionAppService.CreateCollectionAsync(new CreateCollectionInputDto
                    {
                        Intro = worksheet.Cells[row, 2].Value.ToString(),
                        Title = worksheet.Cells[row, 1].Value.ToString()

                    });
                    collections.Add(collection);
                }

                return collections;
            }
        }
    }
}